<route lang="json5">
{
  style: {
    navigationBarTitleText: '倒计时'
  }
}
</route>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'

defineOptions({
  name: 'Countdown',
})

const navigateToAddAnniversary = () => {
  uni.navigateTo({ url: '/pages/anniversary/index' })
}

dayjs.extend(duration)

const coupleStore = useSupabaseCoupleStore()
const timer = ref<NodeJS.Timeout | null>(null)
const currentTime = ref(dayjs())

// 主要倒计时数据
const mainCountdowns = computed(() => {
  if (!coupleStore.profile)
    return []

  const countdowns = []

  // 恋爱天数（正计时）
  if (coupleStore.profile.relationshipStart) {
    const days = currentTime.value.diff(dayjs(coupleStore.profile.relationshipStart), 'day')
    countdowns.push({
      id: 'love-days',
      title: '我们在一起',
      value: days,
      unit: '天',
      type: 'positive',
      color: '#ff6b9d',
      icon: '💕',
    })
  }

  // 下个纪念日倒计时
  const nextAnniversary = coupleStore.upcomingAnniversaries[0]
  if (nextAnniversary) {
    const anniversaryDate = dayjs(nextAnniversary.date)
    const thisYear = currentTime.value.year()
    let nextDate = anniversaryDate.year(thisYear)

    if (nextDate.isBefore(currentTime.value, 'day')) {
      nextDate = nextDate.year(thisYear + 1)
    }

    const days = nextDate.diff(currentTime.value, 'day')
    countdowns.push({
      id: 'next-anniversary',
      title: nextAnniversary.title,
      value: days,
      unit: '天后',
      type: 'countdown',
      color: '#4ecdc4',
      icon: '🎉',
    })
  }

  return countdowns
})

// 详细倒计时（时分秒）
const detailedCountdown = computed(() => {
  const nextAnniversary = coupleStore.upcomingAnniversaries[0]
  if (!nextAnniversary)
    return null

  const anniversaryDate = dayjs(nextAnniversary.date)
  const thisYear = currentTime.value.year()
  let nextDate = anniversaryDate.year(thisYear)

  if (nextDate.isBefore(currentTime.value, 'day')) {
    nextDate = nextDate.year(thisYear + 1)
  }

  const diff = nextDate.diff(currentTime.value)
  const duration = dayjs.duration(diff)

  return {
    title: nextAnniversary.title,
    days: Math.floor(duration.asDays()),
    hours: duration.hours(),
    minutes: duration.minutes(),
    seconds: duration.seconds(),
  }
})

// 生日倒计时
const birthdayCountdowns = computed(() => {
  if (!coupleStore.profile)
    return []

  const countdowns = []
  const users = [coupleStore.profile.user1, coupleStore.profile.user2]

  users.forEach((user) => {
    if (user.birthday) {
      const birthdayDate = dayjs(user.birthday)
      const thisYear = currentTime.value.year()
      let nextBirthday = birthdayDate.year(thisYear)

      if (nextBirthday.isBefore(currentTime.value, 'day')) {
        nextBirthday = nextBirthday.year(thisYear + 1)
      }

      const days = nextBirthday.diff(currentTime.value, 'day')
      const age = thisYear - birthdayDate.year() + (nextBirthday.year() > thisYear ? 1 : 0)

      countdowns.push({
        id: `birthday-${user.id}`,
        name: user.name,
        avatar: user.avatar,
        days,
        age,
        date: nextBirthday.format('MM月DD日'),
      })
    }
  })

  return countdowns.sort((a, b) => a.days - b.days)
})

// 启动定时器
const startTimer = () => {
  timer.value = setInterval(() => {
    currentTime.value = dayjs()
  }, 1000)
}

// 停止定时器
const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

onMounted(() => {
  coupleStore.initProfile()
  startTimer()
})

onUnmounted(() => {
  stopTimer()
})
</script>

<template>
  <view class="countdown-container">
    <!-- 主要倒计时卡片 -->
    <view class="main-countdowns">
      <view
        v-for="countdown in mainCountdowns"
        :key="countdown.id"
        class="countdown-card"
        :style="{ borderColor: countdown.color }"
      >
        <view class="countdown-icon">
          {{ countdown.icon }}
        </view>
        <view class="countdown-content">
          <view class="countdown-title">
            {{ countdown.title }}
          </view>
          <view class="countdown-value" :style="{ color: countdown.color }">
            {{ countdown.value }}
            <text class="countdown-unit">{{ countdown.unit }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 详细倒计时 -->
    <view v-if="detailedCountdown" class="detailed-countdown">
      <view class="section-title">
        {{ detailedCountdown.title }}
      </view>
      <view class="time-blocks">
        <view class="time-block">
          <view class="time-value">
            {{ detailedCountdown.days }}
          </view>
          <view class="time-label">
            天
          </view>
        </view>
        <view class="time-separator">
          :
        </view>
        <view class="time-block">
          <view class="time-value">
            {{ String(detailedCountdown.hours).padStart(2, '0') }}
          </view>
          <view class="time-label">
            时
          </view>
        </view>
        <view class="time-separator">
          :
        </view>
        <view class="time-block">
          <view class="time-value">
            {{ String(detailedCountdown.minutes).padStart(2, '0') }}
          </view>
          <view class="time-label">
            分
          </view>
        </view>
        <view class="time-separator">
          :
        </view>
        <view class="time-block">
          <view class="time-value">
            {{ String(detailedCountdown.seconds).padStart(2, '0') }}
          </view>
          <view class="time-label">
            秒
          </view>
        </view>
      </view>
    </view>

    <!-- 生日倒计时 -->
    <view v-if="birthdayCountdowns.length > 0" class="birthday-section">
      <view class="section-title">
        生日倒计时
      </view>
      <view class="birthday-list">
        <view
          v-for="birthday in birthdayCountdowns"
          :key="birthday.id"
          class="birthday-item"
        >
          <image :src="birthday.avatar" class="birthday-avatar" mode="aspectFill" />
          <view class="birthday-info">
            <view class="birthday-name">
              {{ birthday.name }}
            </view>
            <view class="birthday-date">
              {{ birthday.date }} ({{ birthday.age }}岁)
            </view>
          </view>
          <view class="birthday-countdown">
            <view class="birthday-days">
              {{ birthday.days }}
            </view>
            <view class="birthday-unit">
              天后
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 纪念日列表 -->
    <view v-if="coupleStore.upcomingAnniversaries.length > 1" class="upcoming-section">
      <view class="section-title">
        即将到来的纪念日
      </view>
      <view class="upcoming-list">
        <view
          v-for="anniversary in coupleStore.upcomingAnniversaries.slice(1, 4)"
          :key="anniversary.id"
          class="upcoming-item"
        >
          <view class="upcoming-date">
            {{ dayjs(anniversary.date).format('MM/DD') }}
          </view>
          <view class="upcoming-info">
            <view class="upcoming-title">
              {{ anniversary.title }}
            </view>
            <view class="upcoming-desc">
              {{ anniversary.description || '重要的日子' }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="mainCountdowns.length === 0" class="empty-state">
      <wd-icon name="time" size="64px" color="#ccc" />
      <text class="empty-text">还没有设置纪念日，快去添加吧！</text>
      <wd-button
        type="primary"
        size="small"
        style="margin-top: 16px;"
        @click="navigateToAddAnniversary"
      >
        添加纪念日
      </wd-button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.countdown-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffb6c1 0%, #ffc0cb 50%, #ffb6c1 100%);
  padding: 20px 16px;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 25% 25%, rgba(255, 182, 193, 0.4) 0%, transparent 50%),
      radial-gradient(circle at 75% 75%, rgba(255, 192, 203, 0.4) 0%, transparent 50%),
      radial-gradient(circle at 50% 10%, rgba(255, 255, 255, 0.3) 0%, transparent 30%);
    pointer-events: none;
  }
}

.main-countdowns {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;

  .countdown-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    padding: 24px;
    display: flex;
    align-items: center;
    border-left: 4px solid;
    backdrop-filter: blur(10px);

    .countdown-icon {
      font-size: 32px;
      margin-right: 16px;
    }

    .countdown-content {
      flex: 1;

      .countdown-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }

      .countdown-value {
        font-size: 32px;
        font-weight: 700;
        color: #ff69b4;
        text-shadow: 0 2px 4px rgba(255, 105, 180, 0.3);

        .countdown-unit {
          font-size: 16px;
          font-weight: 400;
          margin-left: 4px;
        }
      }
    }
  }
}

.detailed-countdown {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  backdrop-filter: blur(10px);

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    text-align: center;
    margin-bottom: 20px;
  }

  .time-blocks {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;

    .time-block {
      background: linear-gradient(135deg, #ff69b4, #ff1493);
      border-radius: 16px;
      padding: 12px 8px;
      min-width: 60px;
      text-align: center;
      color: white;
      box-shadow: 0 4px 12px rgba(255, 105, 180, 0.4);

      .time-value {
        font-size: 24px;
        font-weight: 700;
        line-height: 1;
      }

      .time-label {
        font-size: 12px;
        margin-top: 4px;
        opacity: 0.9;
      }
    }

    .time-separator {
      font-size: 24px;
      font-weight: 700;
      color: #ff69b4;
      text-shadow: 0 2px 4px rgba(255, 105, 180, 0.3);
    }
  }
}

.birthday-section,
.upcoming-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
  backdrop-filter: blur(10px);

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
  }
}

.birthday-list {
  .birthday-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .birthday-avatar {
      width: 40px;
      height: 40px;
      border-radius: 20px;
      margin-right: 12px;
    }

    .birthday-info {
      flex: 1;

      .birthday-name {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }

      .birthday-date {
        font-size: 12px;
        color: #666;
      }
    }

    .birthday-countdown {
      text-align: center;

      .birthday-days {
        font-size: 20px;
        font-weight: 600;
        color: #4ecdc4;
      }

      .birthday-unit {
        font-size: 12px;
        color: #666;
      }
    }
  }
}

.upcoming-list {
  .upcoming-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .upcoming-date {
      width: 50px;
      height: 50px;
      background: #45b7d1;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 12px;
      font-weight: 600;
      margin-right: 12px;
    }

    .upcoming-info {
      flex: 1;

      .upcoming-title {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }

      .upcoming-desc {
        font-size: 12px;
        color: #666;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  backdrop-filter: blur(10px);

  .empty-text {
    margin-top: 16px;
    font-size: 14px;
    color: #999;
    text-align: center;
  }
}
</style>
